package com.yhn.controller;

import com.hospital.common.base.Result;
import com.yhn.minio.MinioUtils;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Map;
import java.util.UUID;

/**
 * 板块 Logo 上传到 MinIO，返回对象路径（相对）或可访问链接（按需要切换）。
 */
@RestController
@RequestMapping(value = "/api/sections/upload", produces = MediaType.APPLICATION_JSON_VALUE)
public class UploadController {
    @Resource
    private MinioUtils minioUtils;

    @PostMapping(value = "/logo", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result<String> uploadLogo(@RequestParam("file") MultipartFile file) throws IOException, Exception {
        if (file == null || file.isEmpty()) {
            return Result.fail(40001, "文件不能为空");
        }
        String original = file.getOriginalFilename();
        String ext = "";
        if (StringUtils.hasText(original) && original.contains(".")) {
            ext = original.substring(original.lastIndexOf('.'));
        }
        String day = LocalDate.now().toString().replaceAll("-", "");
        String objectName = "sections/" + day + "/" + UUID.randomUUID().toString().replaceAll("-", "") + ext;
        // 上传到 MinIO，返回对象名
        String saved = minioUtils.uploadFile(file, objectName);

        try {
            // 获取完整的预签名URL
            String presignedUrl = minioUtils.getPresignedUrl(objectName);
            return Result.success("上传成功", presignedUrl);
        } catch (Exception e) {
            // 如果获取预签名URL失败，返回对象名
            return Result.success("上传成功", saved);
        }
    }

    @PostMapping(value = "/logo-url", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result<String> getLogoUrl(@RequestBody Map<String, String> request) throws Exception {
        String objectName = request.get("objectName");
        if (objectName == null || objectName.trim().isEmpty()) {
            return Result.fail(40001, "对象名不能为空");
        }
        String url = minioUtils.getPresignedUrl(objectName);
        return Result.success("获取成功", url);
    }
}


